<template>
  <div class="app-container">
    <el-form :show-message="!($route.query.isInfo || isInfo)" ref="elForm" :disabled="$route.query.isInfo || isInfo"
      :model="formData" :rules="rules" size="medium" label-width="120px">
      <h2 style="text-align: center">年度生产安全事故应急预案演练计划</h2>
      <h4 class="form-header h4">年度生产安全事故应急预案演练计划</h4>
      <el-row :gutter="15">
        <el-col :span="8">
          <el-form-item label="年度" prop="year">
            <el-date-picker type="year" v-model="formData.year" format="yyyy" value-format="yyyy"
              :style="{ width: '100%' }" placeholder="请选择年度" clearable></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="演练目的" prop="purpose">
        <el-input v-model="formData.purpose" type="textarea" placeholder="请输入演练目的" :autosize="{ minRows: 4, maxRows: 4 }"
          :style="{ width: '100%' }"></el-input>
      </el-form-item>
      <h4 class="form-header h4">
        具体工作安排
        <el-button type="primary" plain size="mini" @click="handleAdd">增行</el-button>
        <!-- <el-button type="danger" plain size="mini" @click="handleDele">删行</el-button> -->
      </h4>
      <el-table :data="formData.bos" :border="true" style="width: 100%">
        <el-table-column label="序号" type="index" align="center" />
        <el-table-column label="演练预案" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`bos.${scope.$index}.reservePlan`" :rules="rules.reservePlan">
              <el-input v-model="scope.row.reservePlan" placeholder="请输入演练预案"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="演练负责人" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`bos.${scope.$index}.leaderId`" :rules="rules.leaderId">
              <UserDialog :disabled="$route.query.isInfo || isInfo" @change="changeUser($event, scope.$index)"
                placeholder="请选择演练负责人" v-model="scope.row.leaderId"></UserDialog>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="计划时间" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`bos.${scope.$index}.planTime`" :rules="rules.planTime">
              <el-date-picker v-model="scope.row.planTime" type="month" :disabled="$route.query.isInfo || isInfo"
                format="yyyy-MM" value-format="yyyy-MM" :style="{ width: '100%' }" placeholder="请选择计划时间"
                clearable></el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="演练地点" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`bos.${scope.$index}.place`" :rules="rules.place">
              <el-input v-model="scope.row.place" placeholder="请输入演练地点"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="选择方式" align="center" width="150">
          <template slot-scope="scope">
            <!-- {{ scope.row.type }} -->
            <el-form-item label-width="0" :prop="`bos.${scope.$index}.type`" :rules="rules.type">
              <el-select v-model="scope.row.type" ref="selectRef" @change="changeType($event, scope.$index)" filterable
                placeholder="请选择培训方式">
                <el-option label="人员" value="0" />
                <el-option label="部门" value="1" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column width="200" align="center">
          <div slot="header" slot-scope="scope">
            <div>选择参加人员或部门</div>
          </div>
          <div slot-scope="scope" v-if="scope.row.type == '0'">
            <!-- <el-table-column label="参加人员" align="center">
          <template slot-scope="scope"> -->
            <el-form-item label-width="0" :prop="`bos.${scope.$index}.joinUserId`" :rules="rules.joinUserId">
              <UserDialogSelection :disabled="$route.query.isInfo || isInfo" @change="changeOpen($event, scope.$index)"
                placeholder="请选择参加人员" v-model="scope.row.joinUserId"></UserDialogSelection>
            </el-form-item>
            <!-- </template>
        </el-table-column> -->
            <!-- 外部质量监控 -->
          </div>
          <div slot-scope="scope" v-else>
            <el-form-item label-width="0" :prop="`bos.${scope.$index}.joinUserId`" :rules="rules.joinUserId">
              <el-cascader :ref="'reference' + scope.$index" :style="{ width: '100%' }"
                :props="{ value: 'id', checkStrictly: true, multiple: true }" :show-all-levels="false" placeholder="请选择部门"
                v-model="scope.row.joinUserId" :options="deptOptions" @change="changeCascaderNums"
                @visible-change="visibleChange($event, scope.$index)"></el-cascader>

            </el-form-item>
          </div>

        </el-table-column>

        <el-table-column label="准备工作" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`bos.${scope.$index}.prepareWork`" :rules="rules.prepareWork">
              <el-input v-model="scope.row.prepareWork" placeholder="请输入准备工作"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="演练要求" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`bos.${scope.$index}.requirement`" :rules="rules.requirement">
              <el-input v-model="scope.row.requirement" placeholder="请输入演练要求"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="删除" align="center">
          <template slot-scope="scope">
            <el-button type="danger" plain size="mini" @click="handleDele(scope.$index)">删行</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-col :span="24" v-if="btnShow">
        <el-form-item label-width="0" style="text-align: center; margin-top: 30px">
          <el-button v-if="!($route.query.isInfo || isInfo)" type="primary" @click="submitForm">提交</el-button>
          <el-button :disabled="false" @click="resetForm">返回</el-button>
        </el-form-item>
      </el-col>
    </el-form>
  </div>
</template>

<script>
import {
  safeAccidentDrillAdd,
  safeAccidentDrillManager,
  safeAccidentDrillInfo,
} from "@/api/secure/safeAccidentDrill.js";
import { deptTreeSelect } from "@/api/system/user.js";
export default {
  components: {},
  dicts: ["verify_key_element"],
  props: {
    isInfo: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: "",
    },
    btnShow: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      postOptions: [],
      isIndeterminate: true,
      checkAll: false,
      deptTreeSelect: [],
      formData: {
        year: undefined,
        bos: [
          {
            type: '0',
            requirement: "",
            prepareWork: "",
            joinUserName: "",
            joinUserId: "",
            place: "",
            planTime: "",
            leaderName: "",
            leaderId: "",
            reservePlan: "",
          },
        ],
        purpose: "",
      },
      rules: {
        year: [
          {
            required: true,
            message: "请选择年份",
            trigger: "change",
          },
        ],
        purpose: [
          {
            required: true,
            message: "请输入演练目的",
            trigger: "blur",
          },
        ],
        planTime: [
          {
            required: true,
            message: "请选择计划时间",
            trigger: "change",
          },
        ],
        place: [
          {
            required: true,
            message: "请输入演练地点",
            trigger: "blur",
          },
        ],
        joinUserId: [
          {
            required: true,
            message: "请选择参加人员",
            trigger: "change",
          },
        ],
        leaderId: [
          {
            required: true,
            message: "请选择演练负责人",
            trigger: "change",
          },
        ],
        prepareWork: [
          {
            required: true,
            message: "请输入准备工作",
            trigger: "blur",
          },
        ],
        requirement: [
          {
            required: true,
            message: "请输入演练要求",
            trigger: "blur",
          },
        ],
        reservePlan: [
          {
            required: true,
            message: "请输入演练预案",
            trigger: "blur",
          },
        ],
      },
      userList: [],
      deptOptions: [],
      showGroup: false,
    };
  },
  computed: {},
  watch: {},
  created() {
    if (this.$route.query.isEdit || this.$route.query.isInfo || this.isInfo) {
      this.getDeptTree();

      this.getinfo();

    }
    this.getDeptTree();
  },
  mounted() { },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    changeType(e, i) {
      this.formData.bos[i].joinUserList = []
      if (this.$route.query.isEdit) {
        this.formData.bos[i].content = this.formData.bos[i].content + ' '
        this.formData.bos[i].content = this.formData.bos[i].content.replace(/\s/g, "");
      }
    },
    changeCascaderNums(e) {
      console.log(e);
      this.showGroup = e.length > 0 ? true : false
    },
    visibleChange(e, i) {
      console.log(e, i);
      if (!e && this.showGroup) {
        let arr = this.$refs['reference' + i].getCheckedNodes()
        let list = []
        let label = []
        arr.forEach((item, index) => {
          list.push(item.value)
          label.push(item.label)
        })
        console.log(list);

        this.formData.bos[i].deptIdReplace = list.toString()
        this.formData.bos[i].deptNameReplace = label.toString()
        // this.formData.bos[i].joinUserId = list.toString()
        // this.formData.bos[i].joinUserName = label.toString()
        console.log(this.formData.bos[i].joinUserId, this.formData.bos[i].joinUserName);
      }
    },
    handleAdd() {
      this.formData.bos.push({
        requirement: "",
        prepareWork: "",
        joinUserName: "",
        joinUserId: "",
        place: "",
        planTime: "",
        leaderName: "",
        leaderId: "",
        reservePlan: "",
        type: '0'
      });
    },
    handleDele(e) {
      if (this.formData.bos.length == 1) return;
      this.formData.bos.splice(e, 1);
    },
    changeOpen(e, i) {
      this.formData.bos[i].joinUserName = e.map((i) => i.nickName).join(",");
    },
    changeUser(e, i) {
      this.formData.bos[i].leaderName = e.nickName;
    },
    valueFormat(value) {
      return value[value.length - 1];
    },
    getinfo() {
      return safeAccidentDrillInfo(this.$route.query.id || this.id).then(
        (response) => {
          this.getDeptTree();
          this.formData = response.data;
          this.formData.bos = response.data.vos;
          this.formData.bos.forEach((item) => {
            item.type = item.type.toString();
            let listUesr = []
            // 0是人员1是部门
            if (item.type == 0) {
              item.joinUserId = item.joinUserId.split(",");
            } else {
              let arr = []
              // item.joinUserList.forEach(e => {
              //   arr.push(e.userId)
              // }).deptNameReplace
              item.deptNameReplace = item.joinUserName
              item.deptIdReplace = item.joinUserId
              arr = item.joinUserId.split(",");
              console.log(arr);
              arr.map((i) => {
                console.log(i);
                listUesr.push(this.findParentLot(i));
              });
              console.log(listUesr);
              item.joinUserId = listUesr
            }
          });
          console.log(this.formData.bos);
        }
      );
    },
    // / 创建新数组 返回
    findParentLot(id) {
      const arr = [];
      console.log(this.deptOptions);
      this.deployIdFun(this.deptOptions, id, arr);
      return arr.reverse();
    },
    // 逻辑代码 for循环 判断相同的id 取上级ID
    deployIdFun(options, id, newArr) {
      console.log(options);
      options.forEach((v) => {
        console.log(v);
        if (v.id == id) {
          newArr.push(id);
          console.log(newArr, "newArr");
          if (!v.parentId || v.parentId !== "0") {
            this.deployIdFun(this.deptOptions, v.parentId, newArr);
          }
        } else {
          if (v.children && v.children.length) {
            this.deployIdFun(v.children, id, newArr);
          }
        }
      });
    },
    submitForm() {
      console.log(this.$refs["reference" + 0]);
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          let query = JSON.parse(JSON.stringify(this.formData));
          query.bos.forEach((item, i) => {
            // item.joinUserId = item.joinUserId.join(",");
            if (item.type == "1") {
              item.joinUserId = item.deptIdReplace
              item.joinUserName = item.deptNameReplace
            }else{
              item.joinUserId = item.joinUserId.join(",")
              // item.joinUserName = item.joinUserName.join(",")
            }
          });

          if (this.formData.safeAccidentDrillId != undefined) {
            safeAccidentDrillManager(query).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.resetForm();
            });
          } else {
            safeAccidentDrillAdd(query).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.resetForm();
            });
          }
        }
      });
    },
    resetForm() {
      this.$tab.closeOpenPage();
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-top: 20px !important;
}
</style>
